import { Service } from 'egg';
import { WorkUnit } from '../model/Work_unit';
import { Employee } from '../model/Employee';

export default class WorkUnitService extends Service {
    /**
     * 创建单位
     * @param param 
     */
    public async createWorkUnit(param: any) {
        try{
            param.work_unit_name=this.ctx.helper.trim(param.work_unit_name);
            const checkResult=await this.ctx.model.WorkUnit.findOne<WorkUnit>({attributes:['work_unit_id'],where:{work_unit_name:param.work_unit_name,is_delete:'0'}});
            if(checkResult){
                throw new Error(JSON.stringify({ code: 2, msg: '该单位名称已存在，不能重复添加' }));
            }
            const submitData: any = {};
            //生成主键id
            submitData.work_unit_id = this.ctx.helper.genUUID();
            submitData.work_unit_name = param.work_unit_name;
            submitData.created_by = param.admin_id;
            submitData.is_delete = '0';
            const department_id = param.department_id;
            if (!department_id) {
                const result: any = await this.ctx.model.WorkUnit.create(submitData);
                if (!result) {
                    throw new Error(JSON.stringify({ code: 2, msg: '创建失败' }));
                }
            } else {
                const department_id_list = department_id.split(',');
                const departmentArr: any = [];
                for (let i = 0; i < department_id_list.length; i++) {
                    const item: any = {};
                    //生成部门主键
                    item.unit_department_id = this.ctx.helper.genUUID();
                    item.work_unit_id = submitData.work_unit_id;
                    item.department_id = department_id_list[i];
                    item.is_delete = '0';
                    departmentArr.push(item);
                }
                //新建事务
                const tran = await this.ctx.model.transaction();
                try {
                    await this.ctx.model.WorkUnit.create(submitData, { transaction: tran });
                    if (departmentArr.length > 0) {
                        await this.ctx.model.UnitDepartment.bulkCreate(departmentArr, { transaction: tran });
                    }
                    await tran.commit();
                } catch (e) {
                    await tran.rollback();
                    this.ctx.logger.error(e);
                    throw new Error(JSON.stringify({ code: 2, msg: '创建失败' }));
                }
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 删除单位
     * @param param 
     */
    public async deleteWorkUnit(param: any) {
        try{
            const work_unit_id = param.work_unit_id;
            const searchEmployeeParam = { work_unit_id, type: 1 };
            const employee = await this.searchEmployeeByUnit(searchEmployeeParam);
            if (employee.length > 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '该单位存在职员不能删除，如想删除，请先到职员管理，解绑或者删除相关职员' }));
            }
            const admin_id = param.admin_id;
            const tran = await this.ctx.model.transaction();
            try {
                const deleteResult = await this.ctx.model.WorkUnit.update({ updated_by: admin_id, is_delete: '1' }, { where: { work_unit_id }, transaction: tran });
                if (deleteResult[0] <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '删除失败' }));
                }
                await this.ctx.model.UnitDepartment.destroy({ where: { work_unit_id }, transaction: tran });
                await tran.commit();
            } catch (e) {
                await tran.rollback();
                this.ctx.logger.error(e);
                throw new Error(JSON.stringify({ code: 2, msg: '删除失败' }));
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 查找单位
     * @param param 
     */
    public async searchWorkUnit() {
        try{
            const result: any = await this.ctx.model.WorkUnit.findAll<WorkUnit>({ 
                attributes: ['work_unit_id', 'work_unit_name'], 
                where: { is_delete: '0' },
                order:[['created_at','DESC']]
            });
            if (result.length <= 0) {
                throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
            }
            const returnData: any = [];
            //查找在职员工数
            for (let i = 0; i < result.length; i++) {
                const item: any = {};
                item.work_unit_id = result[i].work_unit_id;
                item.work_unit_name = result[i].work_unit_name;
                const employee:any=await this.ctx.model.Employee.count({where:{work_unit_id:item.work_unit_id,is_delete:'0',employee_status:'2'}});
                item.employee_num = employee;
                returnData.push(item);
            }
            return returnData;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 根据单位id查找单位信息
     * @param param 
     */
    public async searchWorkUnitById(param: any) {
        try{
            const work_unit_id = param.work_unit_id;
            const result: any = await this.ctx.model.WorkUnit.findOne<WorkUnit>({ attributes: ['work_unit_name'], where: { work_unit_id, is_delete: '0' } });
            if (!result) {
                throw new Error(JSON.stringify({ code: 2, msg: '找不到这个单位' }));
            }
            const returnData: any = {};
            returnData.work_unit_id = work_unit_id;
            returnData.work_unit_name = result.WorkUnit;
            const queryStr = `
            select d.department_id,d.department_name from t_unit_department ud inner join t_department d 
            on ud.work_unit_id=:work_unit_id and ud.department_id=d.department_id and d.is_delete='0' where ud.is_delete='0'`;
            const departmentResult: any = await this.ctx.model.query(queryStr, {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { work_unit_id }
            })
            if (departmentResult.length <= 0) {
                returnData.departmentList = [];
            } else {
                returnData.departmentList = departmentResult;
            }
            return returnData;
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 修改单位
     * @param param 
     */
    public async updateWorkUnit(param: any) {
        try{
            param.work_unit_name=this.ctx.helper.trim(param.work_unit_name);
        const queryStr=`select work_unit_id from t_work_unit where work_unit_name=:work_unit_name and is_delete='0' and work_unit_id not in (:work_unit_id)`;
        const checkIsRepeatResult=await this.ctx.model.query(queryStr,{
            type:this.ctx.model.QueryTypes.SELECT,
            replacements:{work_unit_name:param.work_unit_name,work_unit_id:param.work_unit_id}
        });
        if(checkIsRepeatResult.length>0){
            throw new Error(JSON.stringify({ code: 2, msg: '该单位名称已存在，修改失败' }));
        }
        const admin_id = param.admin_id;
        const work_unit_id = param.work_unit_id;
        const work_unit_name = param.work_unit_name;
        const department_id = param.department_id;
        const searchEmployeeParam = { work_unit_id, type: 2 };
        const employee = await this.searchEmployeeByUnit(searchEmployeeParam);
        const department_id_list = department_id.split(',');
        let checkResult=true;
        for(let i=0;i<employee.length;i++){
            let hasDepartment=false;
            for(let j=0;j<department_id_list.length;j++){
                if(employee[i].department_id==department_id_list[j]){
                    hasDepartment=true;
                    break;
                }
            }
            if(hasDepartment){
                continue;
            }else{
                checkResult=false;
            }
        }
        if(!checkResult){
            throw new Error(JSON.stringify({ code: 2, msg: '该单位所属部门存在职员，不能删除有职员的部门，如想删除，请先到职员管理，解绑或者删除相关职员' }));
        }
        if (!department_id) {
            const tran = await this.ctx.model.transaction();
            try {
                const updateResult: any = await this.ctx.model.WorkUnit.update({ work_unit_name, updated_by: admin_id }, { where: { work_unit_id }, transaction: tran });
                if (updateResult[0] <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
                }
                await this.ctx.model.UnitDepartment.destroy({ where: { work_unit_id }, transaction: tran });
                await tran.commit();
            } catch (e) {
                await tran.rollback();
                this.ctx.logger.error(e);
                throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
            }
        } else {
            const department_id_list = department_id.split(',');
            const departmentArr: any = [];
            for (let i = 0; i < department_id_list.length; i++) {
                const item: any = {};
                //生成部门主键
                item.unit_department_id = this.ctx.helper.genUUID();
                item.work_unit_id = work_unit_id;
                item.department_id = department_id_list[i];
                item.is_delete = '0';
                departmentArr.push(item);
            }
            //新建事务
            const tran = await this.ctx.model.transaction();
            try {
                const updateResult: any = await this.ctx.model.WorkUnit.update({ work_unit_name, updated_by: admin_id }, { where: { work_unit_id }, transaction: tran });
                if (updateResult[0] <= 0) {
                    throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
                }
                await this.ctx.model.UnitDepartment.destroy({ where: { work_unit_id }, transaction: tran });
                if (departmentArr.length > 0) {
                    await this.ctx.model.UnitDepartment.bulkCreate(departmentArr, { transaction: tran });
                }
                await tran.commit();
            } catch (e) {
                await tran.rollback();
                this.ctx.logger.error(e);
                throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
            }
        }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }

    /**
     * 根据单位找职员
     * @param param 
     */
    public async searchEmployeeByUnit(param: any) {
        try{
            const work_unit_id = param.work_unit_id;
            const type = param.type;
            if (type == 1) {
                const result: any = await this.ctx.model.Employee.findAll<Employee>({ attributes: ['employee_id'], where: { work_unit_id, is_delete: '0' } });
                return result;
            } else if (type == 2) {
                const queryStr = `select department_id from t_employee where work_unit_id=:work_unit_id and is_delete='0' group by department_id`;
                const result: any = await this.ctx.model.query(queryStr, {
                    type: this.ctx.model.QueryTypes.SELECT,
                    replacements: { work_unit_id }
                })
                return result;
            }
        }catch(e){
            this.ctx.logger.error(e);
            throw new Error(e.message);
        }
    }
}